﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using PWMIS.DataProvider.Adapter ;
using PWMIS.DataProvider.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Security.Cryptography;
using Hisuntech.SystemFramework.Exception;

namespace Hisuntech.SystemFramework.Web
{
    /// <summary>
    /// 大黄数据访问类，仅供兼容原有程序，新程序请勿使用
    /// </summary>
    public class HclDb
    {
        public CommonDB db = null;

        public HclDb()
        {
            db = MyDB.GetDBHelper();
        }

        #region 数据库操作

        //**********************************>> 数据库操作篇 <<**********************************//
        public virtual string GetScalar(string sql)
        {
            object temp = db.ExecuteScalar(sql);
            return temp==null?"":temp.ToString ();
        }
        public virtual DataTable GetDataTable(string sql)
        {
            return db.ExecuteDataSet(sql).Tables[0];
        }
        //数据库插入，删除操作避免了特殊字符带来的错误
        public virtual void Insert(Hashtable ht, string tableName)
        {
            string sql = "Insert Into " + tableName;
            string fields = "";
            string values = "";
            IDataParameter[] paras = new IDataParameter[ht.Count];
            int index = 0;

            foreach (DictionaryEntry de in ht)
            {
                string paraName = "@" + de.Key.ToString();
                fields += de.Key.ToString() + ",";
                values += paraName + ",";
                paras[index] = db.GetParameter(paraName, de.Value);
                index++;
            }
            sql += "(" + fields.TrimEnd(',') + ") Values(" + values.TrimEnd(',') + ")";
            db.ExecuteNonQuery(sql, CommandType.Text, paras);
        }

        /// <summary>
        /// 根据hashtable修改表记录,可以解决特殊字符带来的sql语句造成的错误
        /// </summary>
        /// <param name="ht">hashtable</param>
        /// <param name="tableName">表名</param>
        /// <param name="condition">条件</param>
        /// <returns>受影响的记录数</returns>
        public virtual int Update(Hashtable ht, string tableName, string condition)
        {

            string sql = "Update " + tableName + " Set " ;
            string fields = "";

            IDataParameter[] paras = new IDataParameter[ht.Count];
            int index = 0;

            foreach (DictionaryEntry de in ht)
            {
                string paraName = "@" + de.Key.ToString();
                fields += de.Key.ToString() + "=" + paraName+",";
                paras[index] = db.GetParameter(paraName, de.Value);
                index++;
            }
            sql +=fields.TrimEnd (',');
            if (!string.IsNullOrEmpty(condition))
                sql += " Where "+condition;

           int count= db.ExecuteNonQuery(sql, CommandType.Text, paras);
           return count;

        }

        /// <summary>
        /// 根据sql语句修改数据库,可进行插入,修改,删除操作
        /// </summary>
        /// <param name="arryData">需要操作数据库的sql语句</param>		
        public virtual int Update(string sql)
        {
            return db.ExecuteNonQuery(sql);
        }
        /// <summary>
        /// 该方法未实现，请使用其它重载
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="dt"></param>
        public virtual void Update(string sql, DataTable dt)
        {
           
        }
        /// <summary>
        /// 根据条件更新Hashtable 里面的数据
        /// </summary>
        /// <param name="ht"></param>
        /// <param name="tableName"></param>
        /// <param name="condition"></param>
        public virtual void UpdateInSql(Hashtable ht, string tableName, string condition)
        {
            string sqlAll = "";
            string sqlField = "";
            //string sqlValue = "";
            int i = 0;
            foreach (DictionaryEntry de in ht)
            {
                if (i == 0)
                {
                    sqlField = de.Key.ToString() + "='" + de.Value.ToString() + "'";
                }
                else
                {
                    sqlField += "," + de.Key.ToString() + "='" + de.Value.ToString() + "'";
                }
                i++;
            }
            sqlAll = "update " + tableName + " set " + sqlField + " where " + condition;
            Update(sqlAll);
        }


        public virtual void Delete(string tableName, string condition)
        {
            string sql = "delete from " + tableName + " where " + condition;
            db.ExecuteNonQuery(sql);
        }
        #endregion

        #region 数据统计
        //**********************************>> 数据统计篇 <<**********************************//
        public virtual int GetRsCount(string table_name)
        {
            string strSql;
            int intCount;
            strSql = "select count(*) from " + table_name;
            intCount = int.Parse(GetScalar(strSql));
            return intCount;
        }
        public virtual int GetRsCount(string table_name, string where)
        {
            string strSql;
            int intCount;
            strSql = "select count(*) from " + table_name + " where " + where;
            intCount = int.Parse(GetScalar(strSql));
            return intCount;
        }
        /// 获得单个int类型字段总和
        /// <param name="field">字段</param>
        /// <param name="table_name">表名或者表名+条件,GetFiledSum("id","t_user where id="+Request["id"])</param>
        public virtual string GetFiledSum(string field, string table_name)
        {
            return GetScalar("select sum(" + field + ") as s from " + table_name);
        }

        public virtual string GetFiledStr(string field, string table_name, string condition)
        {
            string val = "";
            DataTable dt = db.ExecuteDataSet("Select " + field + " from " + table_name + " where " + condition).Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i == 0)
                {
                    val = dt.Rows[i][0].ToString();
                }
                else
                {
                    val = val + "," + dt.Rows[i][0].ToString();
                }
            }
            return val;
        }

        #endregion

        #region 控件操作
        //**********************************>> 控件操作篇 <<**********************************//
        public virtual void BindCtrl(int startNumber, int endNumber, Control listctrl)
        {
            //＝＝＝DropDownList＝＝＝
            if (listctrl is DropDownList)
            {
                for (int i = startNumber; i <= endNumber; i++)
                {
                    ((DropDownList)listctrl).Items.Insert(i - startNumber, new ListItem(i.ToString(), i.ToString()));
                }
            }
        }


        public virtual void BindCtrl(string str_Sql, Control ctl_Listctl)
        {//绑定控件
            if (ctl_Listctl is Repeater)
            {
                ((Repeater)ctl_Listctl).DataSource = db.ExecuteDataSet(str_Sql).Tables[0].DefaultView;
                ((Repeater)ctl_Listctl).DataBind();
            }
            if (ctl_Listctl is DataList)
            {
                ((DataList)ctl_Listctl).DataSource = db.ExecuteDataSet(str_Sql).Tables[0].DefaultView;
                ((DataList)ctl_Listctl).DataBind();
            }
            if (ctl_Listctl is DataGrid)
            {
                ((DataGrid)ctl_Listctl).DataSource = db.ExecuteDataSet(str_Sql).Tables[0].DefaultView;
                ((DataGrid)ctl_Listctl).DataBind();
            }
            //			this.DataTableRemove("Table1");
            //			this.Clear();
        }
        public virtual void BindCtrl(string str_Sql, string keyField, Control ctl_Listctl)
        {//绑定控件带主键
            if (ctl_Listctl is Repeater)
            {
                ((Repeater)ctl_Listctl).DataSource = db.ExecuteDataSet(str_Sql).Tables[0].DefaultView;
                ((Repeater)ctl_Listctl).DataBind();
            }
            if (ctl_Listctl is DataList)
            {
                ((DataList)ctl_Listctl).DataSource = db.ExecuteDataSet(str_Sql).Tables[0].DefaultView;
                ((DataList)ctl_Listctl).DataBind();
            }
            if (ctl_Listctl is DataGrid)
            {
                if (keyField != "")
                {
                    ((DataGrid)ctl_Listctl).DataKeyField = keyField;
                }
                ((DataGrid)ctl_Listctl).DataSource = db.ExecuteDataSet(str_Sql).Tables[0].DefaultView;
                ((DataGrid)ctl_Listctl).DataBind();
            }
            //			this.DataTableRemove("Table1");
            //			this.Clear();
        }
        public virtual void BindCtrl(string id, string name, string str_Sql, Control listctrl)
        {//绑定数据库的值到控件上


            DataTable dt = db.ExecuteDataSet(str_Sql).Tables[0];
            //＝＝＝DropDownList＝＝＝
            if (listctrl is DropDownList)
            {
                ((DropDownList)listctrl).DataTextField = name;
                ((DropDownList)listctrl).DataValueField = id;
                ((DropDownList)listctrl).DataSource = dt;
                ((DropDownList)listctrl).DataBind();
            }
            //＝＝＝CheckBoxList＝＝＝
            if (listctrl is CheckBoxList)
            {
                ((CheckBoxList)listctrl).Items.Clear();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ListItem it = new ListItem(dt.Rows[i][name].ToString(), dt.Rows[i][id].ToString());
                    ((CheckBoxList)listctrl).Items.Add(it);
                }
            }
            //＝＝＝RadioButtonList＝＝＝
            if (listctrl is RadioButtonList)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ListItem it = new ListItem(dt.Rows[i][name].ToString(), dt.Rows[i][id].ToString());
                    ((RadioButtonList)listctrl).Items.Add(it);
                }
            }
            //＝＝＝ListBox＝＝＝
            if (listctrl is ListBox)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ListItem it = new ListItem(dt.Rows[i][name].ToString(), dt.Rows[i][id].ToString());
                    ((ListBox)listctrl).Items.Add(it);
                }
            }
            //			this.DataTableRemove("Table2");
            dt.Clear();
        }

        //绑定TreeView,只能绑定自连接表。
        //调用方法：conn.BindCtrl(0,null,"select * from Tb_Sys_Modules where IsMenu='1' and IsManagement='1'","ModuleId","ModuleName","ParentID",this.TreeView1);
        public virtual void BindCtrl(int nFatherid, TreeNode fatherNode, string sql, string ModuleId, string ModuleName, string ParentID, TreeView TreeView1)
        {
            TreeNode NodesAll = GetNodes(nFatherid, fatherNode, sql, ModuleId, ModuleName, ParentID, TreeView1);
            TreeView1.Nodes.Add(NodesAll);
        }

        private DataTable dt = null;
        private TreeNode GetNodes(int nFatherid, TreeNode fatherNode, string sql, string ModuleId, string ModuleName, string ParentID, TreeView TreeView1)
        {
            if (dt == null)
            {
                dt = db.ExecuteDataSet(sql).Tables[0];
            }
            DataView dv = dt.DefaultView;
            DataRow[] dr = dt.Select("[" + ParentID + "] = " + nFatherid);


            TreeNode NodeParent = new TreeNode();
            NodeParent.Value = "0";
            NodeParent.Text = "分类管理";
            foreach (DataRow Row in dr)
            {
                TreeNode node = new TreeNode();
                if (fatherNode == null)//根节点
                {


                    node.Text = Row[ModuleName].ToString() + "[" + Row[ModuleId].ToString() + "]";
                    node.Value = Row[ModuleId].ToString();
                    node.Expanded = true;
                    // node.Expanded = true;
                    //node.NavigateUrl = "javascript:void(0)";

                    NodeParent.ChildNodes.Add(node);
                    //					TreeView1.Nodes.Add(node);   
                    //					TreeView1.Nodes.Add(root);                
                    GetNodes(Int32.Parse(Row[ModuleId].ToString()), node, sql, ModuleId, ModuleName, ParentID, TreeView1);//递归
                }
                else
                {
                    //子节点
                    node.Text = Row[ModuleName].ToString() + "[" + Row[ModuleId].ToString() + "]";
                    node.Value = Row[ModuleId].ToString();
                    node.Expanded = true;
                    // node.Expanded = true;
                    //node.NavigateUrl = "javascript:void(0)";
                    //					node.NavigateUrl="http://www.hao123.com";
                    //					node.Target="_blank";

                    fatherNode.ChildNodes.Add(node);
                    //fatherNode.Expanded=true;
                    GetNodes(Int32.Parse(Row[ModuleId].ToString()), node, sql, ModuleId, ModuleName, ParentID, TreeView1);//递归          
                }
            }
            NodeParent.Expanded = true;
            return NodeParent;
        }



        /// <summary>
        /// 通过treeview节点的ID值选中节点上的checkbox
        /// TreeviewExpand(this.ModuleID,this.TreeView1);
        /// </summary>
        /// <param name="SelectValue"></param>
        /// <param name="TreeView1"></param>
        public void TreeviewChecked(string SelectValue, TreeView TreeView1)
        {
            TreeNode node1 = null;
            foreach (TreeNode node in TreeView1.Nodes)
            {
                node1 =this.DisplayChildNodeText(node, SelectValue);
                if (node1 != null)
                {
                    node1.Checked = true;
                }
            }
        }
        //private TreeNode DisplayChildNodeText(TreeNode nodes, string selectValue)
        //{
        //    TreeNode tn = null;
        //    foreach (TreeNode node2 in nodes.ChildNodes)
        //    {

        //        if (node2.Value == selectValue)
        //        {
        //            tn = node2;
        //            tn.Checked = true;
        //            break;
        //        }
        //        this.DisplayChildNodeText(node2, selectValue);
        //    }
        //    return tn;
        //}




        /// <summary>
        /// 分类绑定到下拉框
        /// BandCtrl("select * from Tb_Sys_Modules order by moduleID","ModuleId","ModuleName","ParentID",this.DropDownList1);
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="ModuleId"></param>
        /// <param name="ModuleName"></param>
        /// <param name="ParentID"></param>
        /// <param name="DropDownList1"></param>
        public virtual void BindCtrl(string sql, string ModuleId, string ModuleName, string ParentID, DropDownList DropDownList1)
        {
            DropDownList1.Items.Clear();
            DataTable dt = db.ExecuteDataSet(sql).Tables[0];
            DataRow[] dr = dt.Select(ParentID + "='0'");
            foreach (DataRow Row in dr)
            {
                DropDownList1.Items.Add(new ListItem(Row[ModuleName].ToString(), Row[ModuleId].ToString()));
                DataRow[] dr1 = dt.Select(ParentID + "=" + Row[ModuleId].ToString());
                foreach (DataRow Row1 in dr1)
                {
                    DropDownList1.Items.Add(new ListItem("|--" + Row1[ModuleName].ToString(), Row1[ModuleId].ToString()));
                    DataRow[] dr2 = dt.Select(ParentID + "=" + Row1[ModuleId].ToString());
                    foreach (DataRow Row2 in dr2)
                    {
                        DropDownList1.Items.Add(new ListItem("　|--" + Row2[ModuleName].ToString(), Row2[ModuleId].ToString()));

                        DataRow[] dr3 = dt.Select(ParentID + "=" + Row2[ModuleId].ToString());
                        foreach (DataRow Row3 in dr3)
                        {
                            DropDownList1.Items.Add(new ListItem("　　|--" + Row3[ModuleName].ToString(), Row3[ModuleId].ToString()));
                            DataRow[] dr4 = dt.Select(ParentID + "=" + Row3[ModuleId].ToString());
                            foreach (DataRow Row4 in dr4)
                            {
                                DropDownList1.Items.Add(new ListItem("　　　|--" + Row4[ModuleName].ToString(), Row4[ModuleId].ToString()));
                                DataRow[] dr5 = dt.Select(ParentID + "=" + Row4[ModuleId].ToString());
                                foreach (DataRow Row5 in dr5)
                                {
                                    DropDownList1.Items.Add(new ListItem("　　　　|--" + Row5[ModuleName].ToString(), Row5[ModuleId].ToString()));
                                }
                            }
                        }
                    }
                }
            }
        }
       

        //单表查询
        public virtual void BindCtrl(string Where, int PageSize, int PageNumber, int AllCount, string Field, string Table, string PK, string Order, Control ctl_Listctl)
        {
            string SQLKey = "";
            if (Order != "")
            {
                SQLKey = "select top " + PageSize + " " + Field + " from " + Table + " where " + PK + " not in ( select top " + PageSize * (PageNumber - 1) + " " + PK + " from " + Table + " where " + Where + " order by " + Order + ") and  " + Where + " order by " + Order + "";
            }
            else
            {
                SQLKey = "select top " + PageSize + " " + Field + " from " + Table + " where " + PK + " not in ( select top " + PageSize * (PageNumber - 1) + " " + PK + " from " + Table + " where " + Where + ") and  " + Where + "";
            }
            //this.Open();
            if (ctl_Listctl is Repeater)
            {
                ((Repeater)ctl_Listctl).DataSource = db.ExecuteDataSet(SQLKey).Tables[0];
                ((Repeater)ctl_Listctl).DataBind();
            }
            if (ctl_Listctl is DataList)
            {
                ((DataList)ctl_Listctl).DataSource = db.ExecuteDataSet(SQLKey).Tables[0];
                ((DataList)ctl_Listctl).DataBind();
            }
            if (ctl_Listctl is DataGrid)
            {
                if (PK != "")
                {
                    ((DataGrid)ctl_Listctl).DataKeyField = PK;
                }
                ((DataGrid)ctl_Listctl).DataSource = db.ExecuteDataSet(SQLKey).Tables[0];
                ((DataGrid)ctl_Listctl).DataBind();
            }
            //cn.Close();
        }



        //public virtual void BindCtrlWithStore(string ProcedureName, Control ctl_Listctl)
        //{//绑定控件
        //    if (ctl_Listctl is Repeater)
        //    {
        //        ((Repeater)ctl_Listctl).DataSource = this.StoredDataTable(ProcedureName).DefaultView;
        //        ((Repeater)ctl_Listctl).DataBind();
        //    }
        //    if (ctl_Listctl is DataList)
        //    {
        //        ((DataList)ctl_Listctl).DataSource = this.StoredDataTable(ProcedureName).DefaultView;
        //        ((DataList)ctl_Listctl).DataBind();
        //    }
        //    if (ctl_Listctl is DataGrid)
        //    {
        //        ((DataGrid)ctl_Listctl).DataSource = this.StoredDataTable(ProcedureName).DefaultView;
        //        ((DataGrid)ctl_Listctl).DataBind();
        //    }
        //}

        //public virtual void BindCtrlWithStore(string ProcedureName, Control ctl_Listctl, IDataParameter[] ParamsData)
        //{//绑定控件
        //    if (ctl_Listctl is Repeater)
        //    {
        //        ((Repeater)ctl_Listctl).DataSource = this.StoredDataTable(ProcedureName, ParamsData).DefaultView;
        //        ((Repeater)ctl_Listctl).DataBind();
        //    }
        //    if (ctl_Listctl is DataList)
        //    {
        //        ((DataList)ctl_Listctl).DataSource = this.StoredDataTable(ProcedureName, ParamsData).DefaultView;
        //        ((DataList)ctl_Listctl).DataBind();
        //    }
        //    if (ctl_Listctl is DataGrid)
        //    {
        //        ((DataGrid)ctl_Listctl).DataSource = this.StoredDataTable(ProcedureName, ParamsData).DefaultView;
        //        ((DataGrid)ctl_Listctl).DataBind();
        //    }
        //}

        public virtual void SelCtrl(string strValueField, Control listctrl)
        {
            if (listctrl is DropDownList)
            {
                //＝＝＝DropDownList＝＝＝
                for (int i = 0; i < ((DropDownList)listctrl).Items.Count; i++)
                {
                    ((DropDownList)listctrl).Items[i].Selected = false;
                }

                for (int i = 0; i < ((DropDownList)listctrl).Items.Count; i++)
                {
                    if (strValueField == ((DropDownList)listctrl).Items[i].Value)
                    {
                        if (((DropDownList)listctrl).Items[i].Selected != true)
                        {
                            ((DropDownList)listctrl).Items[i].Selected = true;
                        }
                        break;
                    }
                }
            }
            //＝＝＝CheckBoxList＝＝＝
            if (listctrl is CheckBoxList)
            {
                for (int i = 0; i < ((CheckBoxList)listctrl).Items.Count; i++)
                {
                    if (strValueField.IndexOf(((CheckBoxList)listctrl).Items[i].Value) != -1)
                    {
                        ((CheckBoxList)listctrl).Items[i].Selected = true;
                    }
                }
            }
            //＝＝＝RadioButtonList＝＝＝
            if (listctrl is RadioButtonList)
            {
                for (int i = 0; i < ((RadioButtonList)listctrl).Items.Count; i++)
                {
                    ((RadioButtonList)listctrl).Items[i].Selected = false;
                }

                for (int i = 0; i < ((RadioButtonList)listctrl).Items.Count; i++)
                {
                    if (strValueField == ((RadioButtonList)listctrl).Items[i].Value)
                    {
                        ((RadioButtonList)listctrl).Items[i].Selected = true;
                        break;
                    }
                }
            }
            //＝＝＝ListBox＝＝＝
            if (listctrl is ListBox)
            {
                for (int i = 0; i < ((ListBox)listctrl).Items.Count; i++)
                {
                    if (strValueField.IndexOf(((ListBox)listctrl).Items[i].Value) != -1)
                    {
                        ((ListBox)listctrl).Items[i].Selected = true;
                    }
                }
            }
        }
        /// 绑定DropDownList，CheckBoxList，RadioButtonList，ListBox控件并选中它值
        /// <param name="strValueField">要选中的值</param>
        /// <param name="id">数据库表字段,一般为该表的主键</param>
        /// <param name="name">数据库表字段,控将显示值</param>
        /// <param name="str_Sql">SQL语句</param>
        /// <param name="ValueOrText">true为按值查询,false为按文本查询</param>
        /// <param name="listctrl">DropDownList，CheckBoxList，RadioButtonList，ListBox控件id值</param>
        public virtual void SelCtrl(string strValueField, string id, string name, string str_Sql, Control listctrl, string ValueOrText)
        {
            // ＝＝＝绑定列表控件＝＝＝
            BindCtrl(id, name, str_Sql, listctrl);

            //＝＝＝DropDownList＝＝＝
            if (listctrl is DropDownList)
            {
                for (int i = 0; i < ((DropDownList)listctrl).Items.Count; i++)
                {
                    ((DropDownList)listctrl).Items[i].Selected = false;
                }
                if (ValueOrText == "Value")
                {
                    ListItem it = ((DropDownList)listctrl).Items.FindByValue(strValueField);
                    if (it != null)
                    {
                        it.Selected = true;
                    }
                }
                else
                {
                    ListItem it = ((DropDownList)listctrl).Items.FindByText(strValueField);

                    if (it != null)
                    {
                        it.Selected = true;
                    }

                }

            }
            //＝＝＝CheckBoxList＝＝＝
            if (listctrl is CheckBoxList)
            {
                for (int i = 0; i < ((CheckBoxList)listctrl).Items.Count; i++)
                {
                    if (strValueField.IndexOf(((CheckBoxList)listctrl).Items[i].Value) != -1)
                    {
                        ((CheckBoxList)listctrl).Items[i].Selected = true;
                    }
                }
            }
            //＝＝＝RadioButtonList＝＝＝
            if (listctrl is RadioButtonList)
            {
                ((RadioButtonList)listctrl).Items[0].Selected = false;
                for (int i = 0; i < ((RadioButtonList)listctrl).Items.Count; i++)
                {
                    if (strValueField == ((RadioButtonList)listctrl).Items[i].Value)
                    {
                        ((RadioButtonList)listctrl).Items[i].Selected = true;
                        break;
                    }
                }
            }
            //＝＝＝ListBox＝＝＝
            if (listctrl is ListBox)
            {
                for (int i = 0; i < ((ListBox)listctrl).Items.Count; i++)
                {
                    if (strValueField.IndexOf(((ListBox)listctrl).Items[i].Value) != -1)
                    {
                        ((ListBox)listctrl).Items[i].Selected = true;
                    }
                }
            }
        }

        /// 获得CheckBoxLis,RadioButtonList,ListBox控件所有选中值并以逗号格开,形式："2,3,4"
        /// </summary>
        /// <param name="listctrl">CheckBoxLis,RadioButtonList,ListBox控件</param>
        /// <param name="type">类型，是想获得Value还是Text值</param>
        /// <returns></returns>
        public virtual string GetCtrlSelValue(Control listctrl, string type)
        {
            string str_Value = "";
            switch (type)
            {
                //＝＝＝要选择的是value＝＝＝
                case "value":
                    {
                        //＝＝＝CheckBoxList＝＝＝
                        if (listctrl is CheckBoxList)
                        {
                            for (int i = 0; i < ((CheckBoxList)listctrl).Items.Count; i++)
                            {
                                if (((CheckBoxList)listctrl).Items[i].Selected == true)
                                {
                                    str_Value = str_Value + ((CheckBoxList)listctrl).Items[i].Value + ",";
                                }
                            }
                            if (str_Value != "")
                            {
                                str_Value = str_Value.Substring(0, str_Value.Length - 1);
                            }
                        }
                        //＝＝＝RadioButtonList＝＝＝
                        if (listctrl is DropDownList)
                        {
                            for (int i = 0; i < ((DropDownList)listctrl).Items.Count; i++)
                            {
                                if (((DropDownList)listctrl).Items[i].Selected == true)
                                {
                                    str_Value = ((DropDownList)listctrl).Items[i].Value;
                                }
                            }

                        }
                        //＝＝＝RadioButtonList＝＝＝
                        if (listctrl is RadioButtonList)
                        {
                            for (int i = 0; i < ((RadioButtonList)listctrl).Items.Count; i++)
                            {
                                if (((RadioButtonList)listctrl).Items[i].Selected == true)
                                {
                                    str_Value = ((RadioButtonList)listctrl).Items[i].Value;
                                }
                            }

                        }
                        //＝＝＝ListBox＝＝＝
                        if (listctrl is ListBox)
                        {

                            for (int i = 0; i < ((ListBox)listctrl).Items.Count; i++)
                            {
                                if (((ListBox)listctrl).Items[i].Selected == true)
                                {
                                    str_Value = str_Value + ((ListBox)listctrl).Items[i].Value + ",";
                                }
                            }
                            if (str_Value != "")
                            {
                                str_Value = str_Value.Substring(0, str_Value.Length - 1);
                            }
                        }
                        break;
                    }
                //＝＝＝要选择的是Text＝＝＝
                case "text":
                    {
                        //＝＝＝CheckBoxList＝＝＝
                        if (listctrl is CheckBoxList)
                        {
                            for (int i = 0; i < ((CheckBoxList)listctrl).Items.Count; i++)
                            {
                                if (((CheckBoxList)listctrl).Items[i].Selected == true)
                                {
                                    str_Value = str_Value + ((CheckBoxList)listctrl).Items[i].Text + ",";
                                }
                            }
                            if (str_Value != "")
                            {
                                str_Value = str_Value.Substring(0, str_Value.Length - 1);
                            }
                        }
                        //＝＝＝RadioButtonList＝＝＝
                        if (listctrl is RadioButtonList)
                        {
                            for (int i = 0; i < ((RadioButtonList)listctrl).Items.Count; i++)
                            {
                                if (((RadioButtonList)listctrl).Items[i].Selected == true)
                                {
                                    str_Value = ((RadioButtonList)listctrl).Items[i].Text;
                                }
                            }

                        }
                        //＝＝＝ListBox＝＝＝
                        if (listctrl is ListBox)
                        {

                            for (int i = 0; i < ((ListBox)listctrl).Items.Count; i++)
                            {
                                if (((ListBox)listctrl).Items[i].Selected == true)
                                {
                                    str_Value = str_Value + ((ListBox)listctrl).Items[i].Text + ",";
                                }
                            }
                            if (str_Value != "")
                            {
                                str_Value = str_Value.Substring(0, str_Value.Length - 1);
                            }
                        }
                        break;
                    }
            }
            return str_Value;

        }
        /// 获得DataGrid控件所有选中列的主键值,并以逗号格开,形式："2,3,4"
        /// </summary>
        /// <param name="CtrName">CheckBox名</param>
        /// <param name="ctrl">DataGrid控件名</param>
        public virtual string GetCtrlSelValue(string CtrName, DataGrid ctrl)
        {
            string str_Value = "";

            foreach (DataGridItem dl in ((DataGrid)ctrl).Items)
            {
                CheckBox chk = (CheckBox)dl.FindControl(CtrName);
                if (chk.Checked)
                {
                    str_Value = str_Value + "," + ctrl.DataKeys[dl.ItemIndex].ToString();
                }
            }
            if (str_Value != "")
            {
                int i = str_Value.Length;
                str_Value = str_Value.Substring(1, i - 1);
            }
            return str_Value;
        }
        /// 获得DataGrid控件所有选中列,显示设置的列值,并以逗号格开,形式："2,3,4"
        /// </summary>
        /// <param name="CellNumber">要显示的是列值</param>
        /// <param name="CtrName">CheckBox名</param>
        /// <param name="ctrl">DataGrid控件名</param>
        public virtual string GetCtrlSelValue(int CellNumber, string CtrName, DataGrid ctrl)
        {
            string str_Value = "";

            foreach (DataGridItem dl in ((DataGrid)ctrl).Items)
            {
                CheckBox chk = (CheckBox)dl.FindControl(CtrName);
                if (chk.Checked)
                {
                    str_Value = str_Value + "," + dl.Cells[CellNumber].Text.ToString();
                }
            }
            if (str_Value != "")
            {
                int i = str_Value.Length;
                str_Value = str_Value.Substring(1, i - 1);
            }
            return str_Value;

        }
        /// <summary>
        /// 选中DataList里的CheckBox返回ID号
        /// </summary>
        /// <param name="CtrName"></param>
        /// <param name="ctrl"></param>
        /// <returns></returns>
        public virtual string GetCtrlSelValue(string CtrName, DataList ctrl)
        {
            string str_Value = "";
            foreach (DataListItem dl in ((DataList)ctrl).Items)
            {
                CheckBox chk = (CheckBox)dl.FindControl(CtrName);
                if (chk.Checked)
                {
                    str_Value = str_Value + "," + chk.Text.ToString();
                }
            }

            if (str_Value != "")
            {
                int i = str_Value.Length;
                str_Value = str_Value.Substring(1, i - 1);
            }
            return str_Value;
        }
        /// 通过一复选框全选全取消某ID值复选框
        /// </summary>
        /// <param name="cb_Id">复选框组ID</param>
        /// <param name="cb_SelectCancel">控制复选框</param>
        /// <param name="ctrl">DataGrid,Repeat,DataList控件id</param>
        public virtual void ChcekAllSel(string cb_Id, CheckBox cb_SelectCancel, Control ctrl)
        {
            if (ctrl is Repeater)
            {
                for (int i = 0; i < ((Repeater)ctrl).Items.Count; i++)
                {
                    CheckBox myCheckBox = (CheckBox)((Repeater)ctrl).Items[i].FindControl(cb_Id);
                    if (cb_SelectCancel.Checked == true)
                    {
                        myCheckBox.Checked = true;
                    }
                    else
                    {
                        myCheckBox.Checked = false;
                    }
                }
            }
            //＝＝＝DataList＝＝＝
            if (ctrl is DataList)
            {
                for (int i = 0; i < ((DataList)ctrl).Items.Count; i++)
                {
                    CheckBox myCheckBox = (CheckBox)((DataList)ctrl).Items[i].FindControl(cb_Id);
                    if (cb_SelectCancel.Checked == true)
                    {
                        myCheckBox.Checked = true;
                    }
                    else
                    {
                        myCheckBox.Checked = false;
                    }
                }
            }
            //＝＝＝DataGrid＝＝＝
            if (ctrl is DataGrid)
            {
                for (int i = 0; i < ((DataGrid)ctrl).Items.Count; i++)
                {
                    CheckBox myCheckBox = (CheckBox)((DataGrid)ctrl).Items[i].FindControl(cb_Id);
                    if (cb_SelectCancel.Checked == true)
                    {
                        myCheckBox.Checked = true;
                    }
                    else
                    {
                        myCheckBox.Checked = false;
                    }
                }
            }
        }
        /// <summary>
        /// 通过treeview节点的ID值展开父节点
        /// TreeviewExpand(this.ModuleID,this.TreeView1);
        /// </summary>
        /// <param name="SelectValue"></param>
        /// <param name="TreeView1"></param>
        public virtual void TreeviewExpand(string SelectValue, TreeView TreeView1)
        {
            TreeNode node1 = null;
            foreach (TreeNode node in TreeView1.Nodes)
            {
                node1 = DisplayChildNodeText(node, SelectValue);
                if (node1 != null)
                {
                    while (node1.Parent != null && node1.Parent is TreeNode)
                    {
                        node1 = (TreeNode)node1.Parent;
                        node1.Expanded = true;
                    }
                    break;
                }
            }
        }

        private TreeNode DisplayChildNodeText(TreeNode nodes, string selectValue)
        {
            TreeNode tn = null;
            foreach (TreeNode node2 in nodes.ChildNodes)
            {

                if (node2.Value == selectValue)
                {
                    tn = node2;
                    break;
                }
                DisplayChildNodeText(node2, selectValue);
            }
            return tn;
        }
        #endregion

        #region 字符操作

        //**********************************>> 字符操作篇 <<**********************************//

        //弹出对话框
        public virtual void WindowOpen(System.Web.UI.Page mypage, string url, int widthX, int heightX)
        {
            often.WindowOpen(mypage, url, widthX, heightX);
        }
        public virtual void WindowClose(System.Web.UI.Page mypage)
        {
            often.WindowClose(mypage);
        }
        public virtual void ShowMessage(System.Web.UI.Page mypage, string info)
        {
            often.ShowMessage(mypage, info);
        }

        public virtual void ShowMessage(System.Web.UI.Page mypage, string info, int type, string url)
        {
            often.ShowMessage(mypage, info, type, url);
        }

        public virtual void Redirect(System.Web.UI.Page mypage, string url)
        {
            often.Redirect(mypage, url);
        }
        public virtual void ReLoad(System.Web.UI.Page mypage)
        {
            often.ReLoad(mypage);
        }
        //字符处理
        public virtual string DatabaseToPage(string strContent)
        {
            return often.DatabaseToPage(strContent);
        }

        public virtual string PageToDatabase(string strContent)
        {
            return often.PageToDatabase(strContent);
        }

        public virtual string GetIP()
        {
            return often.GetIP();
        }
        //日期格式化
        public virtual string GetChineseDateTime(string dateTime)
        {
            return often.GetChineseDateTime(dateTime);
        }
        //获取日期参数所在月份的天数：
        public virtual int GetDaysInMonth(string dateTime)
        {
            return often.GetDaysInMonth(dateTime);
        }

        //过滤特殊字符
        public virtual string StringReplaceDangerCode(string Temp)
        {
            return often.StringReplaceDangerCode(Temp);
        }

        //生成随机数
        public virtual string StringGenerateRandom(int length)
        {
            return often.StringGenerateRandom(length);
        }
        //根据字符拆分字符串，返回字符数组
        public virtual string[] StringSplit(string StringVaule, string Symbol)
        {
            return often.StringSplit(StringVaule, Symbol);
        }
        /// <summary>
        /// 截获定长的字符串
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="length">需要截获的长度</param>
        /// <param name="Symbol">如果字符串被截短，需要添加什么样的后缀</param>
        /// <returns>截获后的字符串</returns>
        public virtual string StringCut(string source, int length, string Symbol)
        {
            return often.StringCut(source, length, Symbol);
        }
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="data">要序列化的对象</param>
        /// <returns>返回存放序列化后的数据缓冲区</returns>
        public virtual byte[] Serialize(object data)
        {
            return often.Serialize(data);
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="data">数据缓冲区</param>
        /// <returns>对象</returns>
        public virtual object Deserialize(byte[] data)
        {
            return often.Deserialize(data);
        }
        /// <summary>
        /// 把一个单元转为大写
        /// </summary>
        /// <param name="Num">这个单元的小写双精度数字</param>
        /// <returns>转换结果</returns>
        public virtual string GetUpper(double Num)
        {
            return often.GetUpper(Num);

        }
        /// <summary>
        /// 	string str1="1,2,3,4,5,7,8";
        ///		string str2="2,3,4,5,6,9,11";
        ///获得字符串str2比str1多出项
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        /// <returns>返回以逗号格开，如： 6,9,11</returns>
        public virtual string StringCompareMore(string str1, string str2)
        {
            return often.StringCompareMore(str1, str2);
        }
        /// <summary>
        /// 	string str1="1,2,3,4,5,7,8";
        ///		string str2="2,3,4,5,6,9,11";
        ///获得字符串str2比str1少的项
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        /// <returns>返回以逗号格开，如：1,7,8</returns>
        public virtual string StringCompareLess(string str1, string str2)
        {
            return often.StringCompareLess(str1, str2);
        }

        //生成随机数
        public virtual string GenerateRandomString(int length)
        {
            return often.GenerateRandomString(length);
        }

        public virtual string GetAppName()
        {
            return often.GetAppName();
        }
        public virtual string StringForMedia(string url, int width, int height)
        {
            return often.StringForMedia(url, width, height);
        }
        #endregion

        #region 加密解密
        public virtual string Encode(string strText)
        {
            return often.Encode(strText);
        }

        public virtual string Decode(string strText)
        {
            return often.Decode(strText);
        }

        public virtual string MD5Encrypt(string strText)
        {
            return often.MD5Encrypt(strText);
        }

        public virtual string MD5Decrypt(string strText)
        {
            return often.MD5Decrypt(strText);
        }
        public virtual string GetMd5(string str)
        {
            return (System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5"));
        }

        public virtual string GetSha1(string str)
        {
            return (System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "sha1"));
        }

        public virtual string Encrypt(string password)
        {
            Byte[] clearBytes = new UnicodeEncoding().GetBytes(password);
            Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);

            return BitConverter.ToString(hashedBytes).ToString();
        }
        #endregion

        #region 文件操作
        /// <summary>
        /// 得到Html源代码
        /// </summary>
        /// <param name="url">网址</param>
        /// <returns>源码</returns>
        public virtual string GetHtmlSource(string url)
        {
            return often.GetHtmlSource(url);
        }
        /// <summary>
        /// 把字符串写到文件里
        ///  string str=GetHtmlSource("http://localhost:8080/interface/servlet/programInfoservlet?qurrycondition=12");
        ///  WriteInfoToFile(str,Server.MapPath("aa.xml"));
        /// </summary>
        /// <param name="Info">字符串</param>
        /// <param name="path">相对路径</param>
        public virtual void WriteInfoToFile(string Info, string path)
        {
            often.WriteInfoToFile(Info, path);
        }

        /// <summary>
        /// 错误日志
        /// </summary>
        /// <param name="ex">错误信息</param>
        /// <param name="type">错误级别</param>
        public virtual void Debug(string ex)
        {
            try
            {
                string localFolder = System.Web.HttpContext.Current.Server.MapPath("~/upload");
                if (!Directory.Exists(localFolder))
                {
                    Directory.CreateDirectory(localFolder);
                }
                if (!File.Exists(localFolder + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt"))
                {
                    StreamWriter sw;
                    using (sw = File.CreateText(localFolder + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt"))
                    {
                        sw.WriteLine(DateTime.Now.ToLongTimeString() + "    " + ex);
                    }
                    sw.Close();
                }
                else
                {
                    StreamWriter sw = new StreamWriter(localFolder + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", true, System.Text.Encoding.UTF8);
                    sw.Write("\r\n" + DateTime.Now.ToLongTimeString() + "    " + ex);
                    sw.Close();
                }
            }
            catch(System.Exception exc)
            {
                ExceptionHandler.HandleException(exc);
            }
        }
        #endregion

        #region 数据处理
        public virtual void DataTableToExcel(System.Data.DataTable dtData)
        {
            often.DataTableToExcel(dtData);
        }

        #endregion
    }
}
